package service

import (
	"file_explorer/common/log"
	"file_explorer/common/util"
	"file_explorer/model"
)

const (
	RenameRuleConfFilename = "rename_rules.yml"
)

func ReadRenameRuleConfs() []*model.RenameRuleConf {
	rawConfs := make([]*model.RawRenameRuleConf, 0)
	err := util.ReadYmlFile(util.PathJoin(util.GetWorkDir(), RenameRuleConfFilename), &rawConfs)
	if err != nil {
		log.Error("read rename rules failed, err=%v", err)
		return nil
	}

	confs := make([]*model.RenameRuleConf, 0, len(rawConfs))
	for _, rawConf := range rawConfs {
		conf := &model.RenameRuleConf{Key: rawConf.Key}
		confs = append(confs, conf)

		for _, raw := range rawConf.Rules {
			conf.Rules = append(conf.Rules, model.BuildRule(raw))
		}
	}

	log.Debug("read rename rules confs success, confNum=%v", len(confs))

	return confs
}

func WriteRenameRuleConf(key string, rules []model.RenameRule) error {
	existConfs := ReadRenameRuleConfs()
	newConfs := make([]*model.RenameRuleConf, 0, 1+len(existConfs))
	newConfs = append(newConfs, &model.RenameRuleConf{
		Key:   key,
		Rules: rules,
	})
	if len(existConfs) > 0 {
		newConfs = append(newConfs, existConfs...)
	}

	err := util.WriteYmlFile(newConfs, util.PathJoin(util.GetWorkDir(), RenameRuleConfFilename))
	if err != nil {
		log.Error("write rename rules failed, err=%v", err)
		return err
	}

	log.Debug("write rename rules success, key=%v", key)

	return nil
}
